<template>
  <div class="user-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <el-form :inline="true" :model="searchForm" class="search-form">
            <el-form-item label="用户名">
              <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable />
            </el-form-item>
            <el-form-item label="角色">
              <el-select v-model="searchForm.roleId" placeholder="请选择角色" clearable style="width: 180px">
                <el-option label="管理员" value="1" />
                <el-option label="普通用户" value="2" />
                <el-option label="审批员" value="3" />
                <el-option label="财务" value="4" />
              </el-select>
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px">
                <el-option label="启用" value="1" />
                <el-option label="禁用" value="0" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-form>
          <el-button type="primary" @click="handleAdd">新增用户</el-button>
        </div>
      </template>

      <el-table :data="tableData" style="width: 100%" v-loading="loading">
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="realName" label="昵称" />
        <el-table-column label="角色">
          <template #default="scope">
            <el-tag v-if="scope.row.roleId === 1" type="danger">管理员</el-tag>
            <el-tag v-else-if="scope.row.roleId === 3" type="warning">审批员</el-tag>
            <el-tag v-else-if="scope.row.roleId === 4" type="success">财务</el-tag>
            <el-tag v-else-if="scope.row.roleId === 2" type="info">普通用户</el-tag>
            <el-tag v-else>{{ scope.row.roleName || scope.row.remark || '未知' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="mobile" label="手机号" />
        <el-table-column label="状态">
          <template #default="scope">
            <el-switch
              :model-value="Number(scope.row.status)"
              :active-value="1"
              :inactive-value="0"
              :loading="scope.row.statusLoading"
              @change="(val) => handleStatusChange({...scope.row, status: val})"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="primary" link @click="handleResetPwd(scope.row)">重置密码</el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 用户表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增用户' : '编辑用户'"
      width="500px"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" :disabled="dialogType === 'edit'" />
        </el-form-item>
        <el-form-item label="昵称" prop="realName">
          <el-input v-model="userForm.realName" />
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="userForm.roleId" style="width: 100%">
            <el-option label="管理员" value="1" />
            <el-option label="普通用户" value="2" />
            <el-option label="审批员" value="3" />
            <el-option label="财务" value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="userForm.mobile" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialogType === 'add'">
          <el-input v-model="userForm.password" type="password" show-password />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="userForm.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="userForm.remark" type="textarea" :rows="2" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { userApi } from '@/api/system'

// 搜索表单
const searchForm = reactive({
  username: '',
  roleId: '',
  status: ''
})

// 表格数据
const loading = ref(false)
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框
const dialogVisible = ref(false)
const dialogType = ref('add')
const userFormRef = ref(null)
const userForm = reactive({
  userId: null,
  username: '',
  realName: '',
  email: '',
  mobile: '',
  password: '',
  status: 1,
  roleId: '',
  remark: '',
  deptId: 103 // 默认部门ID
})

// 表单校验规则
const userRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ],
  roleId: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

// 初始化
onMounted(() => {
  handleSearch()
})

// 搜索方法
const handleSearch = async () => {
  loading.value = true
  try {
    // 构建查询参数，处理空值
    const params = {
      current: currentPage.value,
      size: pageSize.value
    }
    
    // 只添加非空参数
    if (searchForm.username) params.username = searchForm.username
    if (searchForm.roleId) params.roleId = searchForm.roleId
    if (searchForm.status) params.status = searchForm.status
    
    console.log('请求参数:', params)
    const res = await userApi.getList(params)
    console.log('API响应数据:', res)
    
    if (res.data) {
      console.log('响应data字段:', res.data)
      console.log('响应data.records字段:', res.data.records)
      if (Array.isArray(res.data.records)) {
        tableData.value = res.data.records
        total.value = res.data.total || 0
        console.log('设置后的tableData:', tableData.value)
      } else {
        console.warn('res.data.records不是数组:', res.data.records)
        tableData.value = []
        total.value = 0
      }
    } else {
      console.warn('响应中缺少data字段')
      tableData.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取用户列表失败', error)
    ElMessage.error('获取用户列表失败')
    tableData.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  currentPage.value = 1
  handleSearch()
}

// 新增用户
const handleAdd = () => {
  dialogType.value = 'add'
  userForm.userId = null
  userForm.username = ''
  userForm.realName = ''
  userForm.roleId = ''
  userForm.email = ''
  userForm.mobile = ''
  userForm.password = ''
  userForm.status = 1
  userForm.remark = ''
  userForm.deptId = 103 // 默认部门ID
  dialogVisible.value = true
}

// 编辑用户
const handleEdit = (row) => {
  dialogType.value = 'edit'
  userForm.userId = row.userId
  userForm.username = row.username
  userForm.realName = row.realName
  
  // 处理角色数据
  if (row.roleId) {
    userForm.roleId = String(row.roleId)
  } else if (row.roleIds && Array.isArray(row.roleIds) && row.roleIds.length > 0) {
    // 如果有多个角色，取第一个
    userForm.roleId = String(row.roleIds[0])
  } else {
    // 备选处理，尝试从备注判断角色
    const roleMapping = {
      '超级管理员': '1',
      '信贷经理': '2',
      '风控专员': '3',
      '财务专员': '4'
    }
    userForm.roleId = roleMapping[row.remark] || '2' // 默认普通用户
  }
  
  userForm.email = row.email
  userForm.mobile = row.mobile
  userForm.status = row.status
  userForm.remark = row.remark || ''
  userForm.deptId = row.deptId || 103 // 如果存在使用现有的，否则使用默认值
  dialogVisible.value = true
}

// 删除用户
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确认删除该用户吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await userApi.delete(row.userId)
      ElMessage.success('删除成功')
      handleSearch()
    } catch (error) {
      console.error('删除失败', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 重置密码
const handleResetPwd = (row) => {
  ElMessageBox.confirm(
    '确认重置该用户的密码吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await userApi.resetPassword({ userId: row.userId })
      ElMessage.success('密码重置成功')
    } catch (error) {
      console.error('密码重置失败', error)
      ElMessage.error('密码重置失败')
    }
  }).catch(() => {})
}

// 修改状态
const handleStatusChange = async (row) => {
  // 设置当前行的状态为加载中
  tableData.value.forEach(item => {
    if (item.userId === row.userId) {
      item.statusLoading = true;
    }
  });
  
  try {
    // 确保roleId有值
    const roleId = row.roleId ? Number(row.roleId) : 2; // 默认为普通用户
    
    // 构建更新数据，只包含必要字段
    const updateData = {
      userId: row.userId,
      status: row.status,
      // 以下是必要字段，避免后端验证失败
      username: row.username,
      realName: row.realName,
      email: row.email,
      mobile: row.mobile,
      roleId: roleId
    }
    
    console.log('状态更新数据:', updateData)
    await userApi.update(updateData)
    ElMessage.success(`用户状态${row.status === 1 ? '启用' : '禁用'}成功`)
    
    // 更新本地行的状态
    tableData.value.forEach(item => {
      if (item.userId === row.userId) {
        item.status = row.status;
      }
    });
  } catch (error) {
    console.error('状态修改失败', error)
    ElMessage.error('状态修改失败')
    // 恢复原状态（本地状态回滚）
    tableData.value.forEach(item => {
      if (item.userId === row.userId) {
        item.status = item.status === 1 ? 0 : 1;
      }
    });
  } finally {
    // 无论成功或失败，都取消加载状态
    tableData.value.forEach(item => {
      if (item.userId === row.userId) {
        item.statusLoading = false;
      }
    });
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!userFormRef.value) return
  await userFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 构建提交数据，转换数据类型
        const submitData = {
          userId: userForm.userId,
          username: userForm.username,
          realName: userForm.realName,
          email: userForm.email,
          mobile: userForm.mobile,
          status: Number(userForm.status),
          roleId: Number(userForm.roleId),
          remark: userForm.remark,
          deptId: userForm.deptId
        }

        // 新增用户时处理多角色和密码
        if (dialogType.value === 'add') {
          submitData.password = userForm.password
          // API需要roleIds数组，但UI是单选，所以将单个roleId放入数组
          submitData.roleIds = [submitData.roleId]
          // 删除单个roleId，因为API要求使用roleIds
          delete submitData.roleId
        }

        console.log('提交的用户数据:', submitData)

        if (dialogType.value === 'add') {
          await userApi.add(submitData)
          ElMessage.success('添加成功')
        } else {
          await userApi.update(submitData)
          ElMessage.success('修改成功')
        }
        dialogVisible.value = false
        handleSearch()
      } catch (error) {
        console.error(dialogType.value === 'add' ? '添加失败' : '修改失败', error)
        ElMessage.error(dialogType.value === 'add' ? '添加失败' : '修改失败')
      }
    }
  })
}

// 分页方法
const handleSizeChange = (val) => {
  pageSize.value = val
  handleSearch()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  handleSearch()
}
</script>

<style scoped>
.user-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.search-form {
  margin-right: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 